package net.hn.hnms.biz.safety.trinity.group.service;

import net.hn.hnms.biz.api.safety.trinity.model.DangerInfoVo;
import net.hn.hnms.biz.api.safety.trinity.model.TreeViolationsManagementVo;
import net.hn.hnms.biz.safety.trinity.dao.*;
import net.hn.hnms.biz.safety.trinity.entity.*;
import net.hn.hnms.biz.safety.trinity.group.domain.dto.HiddanDangerDto;
import net.hn.hnms.biz.safety.trinity.group.domain.dto.NameAndIntegerDto;
import net.hn.hnms.biz.safety.trinity.group.domain.vo.*;
import net.hn.hnms.biz.safety.trinity.group.mapper.HiddenDangerListMapper;
import net.hn.hnms.biz.safety.trinity.until.Dictionaries;
import net.hn.hnms.biz.safety.trinity.until.MineName;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.constant.MineBaseConstants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.redis.domain.SysOrganization;
import net.hn.hnms.sys.common.redis.domain.SysOrganizationVo;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import net.hn.hnms.sys.system.api.domain.SysDictData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 智呈物联 nzw
 * @date 2023/4/7
 */
@Service
public class HiddanDangerGroupService {

    HiddenDangerListDao hiddenDangerListDao;

    HiddenDangerAcceptDao hiddenDangerAcceptDao;

    HiddenDangerReformDao hiddenDangerReformDao;

    RiskControlListDao riskControlListDao;

    MineName mineName;

    WorkSafetyViolationDao workSafetyViolationDao;
    JdbcTemplate jdbcTemplate;

    @Resource
    private HiddenDangerListMapper hiddenDangerListMapper;

    @Autowired
    public void setHiddenDangerListDao(HiddenDangerListDao hiddenDangerListDao) {
        this.hiddenDangerListDao = hiddenDangerListDao;
    }
    @Autowired
    public void setHiddenDangerListDao( RiskControlListDao riskControlListDao) {
        this.riskControlListDao = riskControlListDao;
    }
    @Autowired
    public void setHiddenDangerAcceptDao(HiddenDangerAcceptDao hiddenDangerAcceptDao) {
        this.hiddenDangerAcceptDao = hiddenDangerAcceptDao;
    }

    @Autowired
    public void setHiddenDangerReformDao(HiddenDangerReformDao hiddenDangerReformDao) {
        this.hiddenDangerReformDao = hiddenDangerReformDao;
    }
    @Autowired
    public void setRiskControlListDao(RiskControlListDao riskControlListDao) {
        this.riskControlListDao = riskControlListDao;
    }
    @Autowired
    public void setWorkSafetyViolationDao(WorkSafetyViolationDao workSafetyViolationDao) {
        this.workSafetyViolationDao = workSafetyViolationDao;
    }

    @Autowired
    public void setMineName(MineName mineName) {
        this.mineName = mineName;
    }
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<HiddenDangerpopUpPromptVO> hiddenDangerpopUpPrompt(String companyCode){
        List<HiddenDangerpopUpPromptVO> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 30);
        String dataTime = simpleDateFormat.format(calendar.getTime());
        List<String> mineCodes=new ArrayList<>();

        for (String key : MineBaseConstants.mineMap.keySet()) {
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
                continue;
            }
            HiddenDangerpopUpPromptVO hiddenDangerpopUpPromptVO = new HiddenDangerpopUpPromptVO();
            BeanUtils.copyProperties(mine, hiddenDangerpopUpPromptVO);
            list.add(hiddenDangerpopUpPromptVO);
            mineCodes.add(mine.getMineCode());
        }
        //新增隐患
        List<Map<String,Object>> hiddenDangerCount = hiddenDangerListDao.findAllLikeDataTimeByMineCode(dataTime,companyCode);

        //累计验收通过的隐患
        List<Map<String,Object>> hiddenDangerAccepts = hiddenDangerListDao.closedLoopCountByMineCode(companyCode);

        hiddenDangerCount.forEach(map->{
            HiddenDangerpopUpPromptVO hiddenDangerpopUpPromptVO=list.get(mineCodes.indexOf(map.get("mine_code")));
            hiddenDangerpopUpPromptVO.setAddHiddenDangerNum(map.get("count")+"");
//            list.add(hiddenDangerpopUpPromptVO);
        });

        hiddenDangerAccepts.forEach(map->{
            HiddenDangerpopUpPromptVO hiddenDangerpopUpPromptVO=list.get(mineCodes.indexOf(map.get("mine_code")));
            hiddenDangerpopUpPromptVO.setOverHiddenDangerNum(map.get("count")+"");
//            list.add(hiddenDangerpopUpPromptVO);
        });

        return list;
    }

    public HiddenDangerVarietyVO hiddenDangerVariety(String companyCode){

        //新增隐患
        List<Map<String,Object>> hiddenDangerCount = hiddenDangerListDao.findAllByDataTime(companyCode);
        //累计验收通过的隐患
        List<Map<String,Object>> hiddenDangerAccepts = hiddenDangerListDao.closedLoopCountByDataTime(companyCode);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 30);

        List<String> dateList = new ArrayList<>(35);
        List<String> addHiddenDangerNum = new ArrayList<>(35);
        List<String> overHiddenDangerNum = new ArrayList<>(35);
        for (int i=0;i<30;i++){
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
            String date = simpleDateFormat.format(calendar.getTime());
            dateList.add(date);

            Map<String,Object> hiddenDangerCountMap = hiddenDangerCount.stream()
                    .filter(l->date.equals(l.get("dataTime")+""))
                    .findFirst()
                    .orElse(null);
            if (hiddenDangerCountMap == null){
                addHiddenDangerNum.add("0");
            }else {
                addHiddenDangerNum.add(hiddenDangerCountMap.get("count")+"");
            }

            Map<String,Object> hiddenDangerAcceptMap = hiddenDangerAccepts.stream()
                    .filter(l->date.equals(l.get("dataTime")+""))
                    .findFirst()
                    .orElse(null);
            if (hiddenDangerAcceptMap == null){
                overHiddenDangerNum.add("0");
            }else {
                overHiddenDangerNum.add(hiddenDangerCountMap.get("count")+"");
            }
        }
        HiddenDangerVarietyVO hiddenDangerVarietyVO = new HiddenDangerVarietyVO();
        hiddenDangerVarietyVO.setAddHiddenDangerNum(addHiddenDangerNum);
        hiddenDangerVarietyVO.setOverHiddenDangerNum(overHiddenDangerNum);
        hiddenDangerVarietyVO.setDate(dateList);

        return hiddenDangerVarietyVO;

    }

    public List<HiddenDangerMajorStateVO> hiddenDangerMajorState(){
        List<HiddenDangerMajorStateVO> list = new ArrayList<>(26);
        List<Map<String,Object>> hiddenDangerMajorList = hiddenDangerListDao.countAllLevelByMineCode();
        List<Map<String,Object>> overdueMajorHiddenDangerList = hiddenDangerListDao.countOverdueMajorHiddenDangerByMineCode();

        hiddenDangerMajorList.forEach(map -> {
            HiddenDangerMajorStateVO hiddenDangerMajorStateVO = new HiddenDangerMajorStateVO();
            String mineCode = map.get("mine_code")+"";
            hiddenDangerMajorStateVO.setMineCode(mineCode);
            hiddenDangerMajorStateVO.setMajorHiddenDanger(map.get("count")+"");
            list.add(hiddenDangerMajorStateVO);
        });

        overdueMajorHiddenDangerList.forEach(map->{
            String mineCode = map.get("mine_code")+"";
            HiddenDangerMajorStateVO hiddenDangerMajorStateVO = list
                    .stream()
                    .filter(l->mineCode.equals(l.getMineCode()))
                    .findFirst()
                    .orElse(new HiddenDangerMajorStateVO());
            hiddenDangerMajorStateVO.setMineCode(mineCode);
            hiddenDangerMajorStateVO.setOverdueMajorHiddenDanger(map.get("count")+"");
            list.add(hiddenDangerMajorStateVO);
        });

        list.forEach(map->{
            String mineCode = map.getMineCode();
            map.setMineName(mineName.getMineName(mineCode));
            map.setCompanyName(mineName.getParentMineName(mineCode));
        });
        return list;
    }

    public GroupLevelCount riskLevelByMineCode(String companyCode){
//        List<String> mineCodes = riskControlListDao.riskMineCode();
        GroupLevelCount count=new GroupLevelCount();
        for (String key: MineBaseConstants.mineMap.keySet()){
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
                continue;
            }
            List<Map<String,Object>> list = riskControlListDao.riskLevelByMineCode(mine.getMineCode());
            GroupLevelCount.MineLevelCount mineLevelCount = dealWithRiskLevel(list, count);
            BeanUtils.copyProperties(mine,mineLevelCount);
            count.setMajor(count.getMajor()+mineLevelCount.getMajor());
            count.setNormalA(count.getNormalA()+mineLevelCount.getNormalA());
            count.setNormalB(count.getNormalB()+mineLevelCount.getNormalB());
            count.setNormalC(count.getNormalC()+mineLevelCount.getNormalC());
            count.getMineLevelCountList().add(mineLevelCount);
        }

        return count;
    }

    /**
     * 风险等级处理
     * @param list 风险列表
     * @return 处理后的风险对象
     */
    private    GroupLevelCount.MineLevelCount dealWithRiskLevel(List<Map<String,Object>> list,GroupLevelCount groupLevelCount){
        GroupLevelCount.MineLevelCount riskLevelCountVO = groupLevelCount.new MineLevelCount();

        for (Map<String,Object> map :list){
            String level = map.get("risk_level")+"";
            String count = "";
            if (map.get("count")!=null&&!"".equals(map.get("count"))){
                count = map.get("count")+"";
            }else {
                count = "0";
            }
            switch (level){
                case "4":
                    riskLevelCountVO.setMajor(Integer.parseInt(count));
                    break;
                case "3":
                    riskLevelCountVO.setNormalA(Integer.parseInt(count));
                    break;
                case "2":
                    riskLevelCountVO.setNormalB(Integer.parseInt(count));
                    break;
                case "1":
                    riskLevelCountVO.setNormalC(Integer.parseInt(count));
                    break;
            }
        }
        return riskLevelCountVO;
    }
    public TreeViolationsManagementVo threeViolations(String companyCode) {
        TreeViolationsManagementVo treeViolationsManagementVo = new TreeViolationsManagementVo();
        //三违总数
        treeViolationsManagementVo.setViolationCount(workSafetyViolationDao.countAllByCompanyCode(companyCode));

        List<Map<String, Object>> list = workSafetyViolationDao.threeViolationsByCompanyCode(companyCode);
        for (Map map : list) {
            if (map.get("violation_level") != null) {
                String violationLevel = map.get("violation_level") + "";
                if (violationLevel.equals("0001")) {
                    treeViolationsManagementVo.setSerious(Integer.parseInt(map.get("count") + ""));
                    continue;
                }
                if (violationLevel.equals("0002")) {
                    treeViolationsManagementVo.setLarger(Integer.parseInt(map.get("count") + ""));
                    continue;
                }
                if (violationLevel.equals("0003")) {
                    treeViolationsManagementVo.setGenerally(Integer.parseInt(map.get("count") + ""));
                    continue;
                }
            } else {
                continue;
            }
        }
        return treeViolationsManagementVo;
    }

    public List<MineHiddenCount> hiddenDangerSum(String companyCode, Date startTime, Date endTime){
//        StringBuilder sb=new StringBuilder("SELECT mine_code,count(1) from hidden_danger_list WHERE 1=1 ");
//        if(StringUtils.isNotBlank(companyCode)){
//            sb.append(" and company_code='").append(companyCode).append("' ");
//        }
//        if(StringUtils.isNotBlank(startTime)){
//            sb.append(" and check_date>='").append(startTime).append("' ");
//        }
//        if(StringUtils.isNotBlank(endTime)){
//            sb.append(" and check_date<='").append(endTime).append("' ");
//        }
//        sb.append(" group by mine_code");
//        List<MineHiddenCount> list = new ArrayList<>();
//        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sb.toString());
//        for (String key : MineBaseConstants.mineMap.keySet()) {
//            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
//            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
//                continue;
//            }
//            MineHiddenCount count=new MineHiddenCount();
//            count.setMineName(mine.getMineName());
//            for (Map<String, Object> map:maps){
//                if(mine.getMineCode().equals(map.get("mine_code"))){
//                    count.setBigDecimal(new BigDecimal(map.get("count")+""));
//                    break;
//                }
//            }
//            list.add(count);
//        }
        //煤矿集合
        List<SysOrganizationVo> list = new ArrayList<>();

        if (StringUtils.isNotBlank(companyCode)) {
            //查询当前公司下面的所有煤矿
            //获取当前公司信息
            SysOrganizationVo sysOrganizationVo = RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + companyCode);
            if (sysOrganizationVo == null) {
                throw new HuaNengException(Constants.FAIL, "无法获取当前公司的子煤矿信息，请检查词典" + companyCode);
            }
            //遍历当前公司下面的所有煤矿
             list = sysOrganizationVo.getSubCodeList();
        } else {
            //查询煤业下面的所有煤矿
            //查询所有公司
            SysOrganizationVo sysOrganizationVo = RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + 0);
            if (sysOrganizationVo == null) {
                throw new HuaNengException(Constants.FAIL, "无法获取所有公司信息，请检查词典" + companyCode);
            }
            //遍历当前公司下面的所有煤矿
            List<SysOrganizationVo> subCodeList = sysOrganizationVo.getSubCodeList();
            for (SysOrganizationVo organizationVo : subCodeList) {
                List<SysOrganizationVo> subCodeList1 = organizationVo.getSubCodeList();
                for (SysOrganizationVo organizationVo1 : subCodeList1) {
                    list.add(organizationVo1);
                }
            }
        }
        List<MineHiddenCount> vo = new ArrayList<>();

        // 查询当前煤矿的 隐患总数
        for (SysOrganizationVo sysOrganizationVo : list) {
            MineHiddenCount mineHiddenCount = new MineHiddenCount();
            // 查询当前煤矿的 隐患总数
            String orgCode = sysOrganizationVo.getOrgCode();
            String orgName = sysOrganizationVo.getOrgName();
            Integer integer = hiddenDangerListMapper.addHiddenDangerCount(null, orgCode, startTime, endTime);

            mineHiddenCount.setMineName(orgName);
            mineHiddenCount.setBigDecimal(new BigDecimal(integer));
            vo.add(mineHiddenCount);
        }

        return vo;
    }

    /**
     * 隐患列表分页查询
     * @param pageQuery
     * @param hiddanDangerDto
     * @return
     */
    public ResponsePage<HiddanDangerVo> hiddenDangerListPageList(PageQuery pageQuery, HiddanDangerDto hiddanDangerDto) {
        if (pageQuery.getPageNum() == null) {
            pageQuery.setPageNum(0);
        }
        if (pageQuery.getPageSize() == null) {
            pageQuery.setPageSize(10);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        if (hiddanDangerDto.getStartDay() == null) {
            Date startDate = null;
            try {
                 startDate = simpleDateFormat.parse("2000-01-01");

//                // 获取当前日期
//                Calendar calendar = Calendar.getInstance();
//                // 将日期设置为今年的第一天
//                calendar.set(Calendar.MONTH, Calendar.JANUARY);
//                calendar.set(Calendar.DAY_OF_MONTH, 1);
//
//                // 获取今年的第一天
//                startDate = calendar.getTime();

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            hiddanDangerDto.setStartDay(startDate);
        }
        if (hiddanDangerDto.getEndDay() == null) {
            hiddanDangerDto.setEndDay(new Date());
        }
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);
        //分页查询风险列表
        List<HiddanDangerVo> hiddanDangerVoList = hiddenDangerListMapper.selectListPage(pageQuery,hiddanDangerDto);
        Integer total = 0;
        if (!hiddanDangerVoList.isEmpty()) {
            HiddanDangerVo hiddanDangerVo = hiddanDangerVoList.get(0);
            total = hiddanDangerVo.getTotal();

            for (HiddanDangerVo dangerVo : hiddanDangerVoList) {
                //隐患等级
                String hiddanDangerLevel = dangerVo.getHiddanDangerLevel();
                //获取等级词典 redis  sys_dict:danger_level
                List<SysDictData> sysDictDataList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "danger_level");
                //词典不为空
                if (!sysDictDataList.isEmpty()) {
                    //字段不为空
                    if (StringUtils.isNotBlank(hiddanDangerLevel)) {
                        for (SysDictData sysDictData : sysDictDataList) {
                            if (sysDictData.getDictValue().equals(hiddanDangerLevel)) {
                                dangerVo.setHiddanDangerLevel(sysDictData.getDictLabel());
                            }
                        }
                    }
                }
                //煤矿编码
                String mineCode = dangerVo.getMineCode();
                if (StringUtils.isNotBlank(mineCode)) {
                    SysOrganization sysOrganization = RedisUtils.getCacheObject(Constants.SYS_CODE_KEY + mineCode);
                    if (sysOrganization != null) {
                        dangerVo.setMineName(sysOrganization.getOrgName());
                    }
                }

                //公司编码
                String companyCode = dangerVo.getCompanyCode();
                if (StringUtils.isNotBlank(companyCode)) {
                    SysOrganization sysOrganization = RedisUtils.getCacheObject(Constants.SYS_CODE_KEY + companyCode);
                    if (sysOrganization != null) {
                        dangerVo.setCompanyName(sysOrganization.getOrgName());
                    }
                }
            }

            return new ResponsePage<>(hiddanDangerVoList, total);
        }
        return new ResponsePage<>(new ArrayList(), total);
    }

    /**
     * 根据隐患状态统计
     * @return
     */
    public HiddenDangerStatusCountVo selectStatusSumByhiddenDangerStatus(String companyCode, String mineCode, Date startDate, Date endDate) {
        HiddenDangerStatusCountVo hiddenDangerStatusCountVo = new HiddenDangerStatusCountVo(0,0,0,0,0,0,0);
        if (StringUtils.isNotBlank(mineCode)) {
            companyCode = null;
        }
        if (StringUtils.isNotBlank(companyCode)) {
            mineCode = null;
        }

        List<NameAndIntegerDto> list = hiddenDangerListMapper.selectStatusSumByhiddenDangerStatus(mineCode,companyCode,startDate, endDate);
        for (NameAndIntegerDto nameAndIntegerDto : list) {
            if ("待五落实".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setWaitFive(nameAndIntegerDto.getValue());
            } else if ("落实退回".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setFiveBack(nameAndIntegerDto.getValue());
            }else if ("待返单".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setWaitReturn(nameAndIntegerDto.getValue());
            }else if ("延期审批".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setDelayApproval(nameAndIntegerDto.getValue());
            }else if ("待复查".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setWaitReview(nameAndIntegerDto.getValue());
            }else if ("待销号".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setWaitDelete(nameAndIntegerDto.getValue());
            } else if ("已闭合".equals(nameAndIntegerDto.getName())) {
                hiddenDangerStatusCountVo.setClose(nameAndIntegerDto.getValue());
            } else {

            }
        }
        return hiddenDangerStatusCountVo;
    }

    /**
     * 根据隐患等级统计
     * @return
     */
    public HiddenDangerLevelCountVo selectlevelSumByhiddenDangerLevel(String companyCode, String mineCode , Date startDate, Date endDate) {
        if (StringUtils.isNotBlank(mineCode)) {
            companyCode = null;
        }
        if (StringUtils.isNotBlank(companyCode)) {
            mineCode = null;
        }
        HiddenDangerLevelCountVo hiddenDangerLevelCountVo = new HiddenDangerLevelCountVo(0,0,0,0);
        List<NameAndIntegerDto> list = hiddenDangerListMapper.selectlevelSumByhiddenDangerLevel(mineCode,companyCode,startDate, endDate);
        for (NameAndIntegerDto nameAndIntegerDto : list) {
            if ("重大".equals(nameAndIntegerDto.getName())) {
                hiddenDangerLevelCountVo.setMajor(nameAndIntegerDto.getValue());
            }else if ("A".equals(nameAndIntegerDto.getName())){
                hiddenDangerLevelCountVo.setGeneralA(nameAndIntegerDto.getValue());

            }else if ("B".equals(nameAndIntegerDto.getName())) {
                hiddenDangerLevelCountVo.setGeneralB(nameAndIntegerDto.getValue());

            } else if ("C".equals(nameAndIntegerDto.getName())) {
                hiddenDangerLevelCountVo.setGeneralC(nameAndIntegerDto.getValue());
            } else {
            }
        }
        return hiddenDangerLevelCountVo;
    }

    /**
     * 根据公司统计隐患等级数量
     * @param companyCode
     * @param startDay
     * @param endDay
     * @return
     */
    public List<SelectlevelSumByCompanyVo> selectlevelSumByCompany(String companyCode, Date startDay, Date endDay) {
        //判断 公司编码是否为空，如果为空 则查询所有公司
        List<SelectlevelSumByCompanyVo> voList = new ArrayList<>();
        if (StringUtils.isNotBlank(companyCode)) {
            //不为空  查询所有煤矿
            //获取当前公司信息
            SysOrganizationVo sysOrganizationVo = RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + companyCode);
            if (sysOrganizationVo == null) {
                throw new HuaNengException(Constants.FAIL, "无法获取当前公司的子煤矿信息，请检查词典" + companyCode);
            }
            //遍历当前公司下面的所有煤矿
            List<SysOrganizationVo> subCodeList = sysOrganizationVo.getSubCodeList();
            for (SysOrganizationVo organizationVo : subCodeList) {
                SelectlevelSumByCompanyVo selectlevelSumByCompanyVo = new SelectlevelSumByCompanyVo();
                String orgName = organizationVo.getOrgName();
                String orgCode = organizationVo.getOrgCode();
                HiddenDangerLevelCountVo hiddenDangerLevelCountVo = this.selectlevelSumByhiddenDangerLevel(null, orgCode, startDay, endDay);
                selectlevelSumByCompanyVo.setCode(orgCode);
                selectlevelSumByCompanyVo.setName(orgName);
                selectlevelSumByCompanyVo.setHiddenDangerLevelCountVo(hiddenDangerLevelCountVo);
                voList.add(selectlevelSumByCompanyVo);
            }
        } else {
            //查询所有公司
            SysOrganizationVo sysOrganizationVo = RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + 0);
            if (sysOrganizationVo == null) {
                throw new HuaNengException(Constants.FAIL, "无法获取所有公司信息，请检查词典" + companyCode);
            }
            //遍历当前公司下面的所有煤矿
            List<SysOrganizationVo> subCodeList = sysOrganizationVo.getSubCodeList();
            for (SysOrganizationVo organizationVo : subCodeList) {
                SelectlevelSumByCompanyVo selectlevelSumByCompanyVo = new SelectlevelSumByCompanyVo();
                String orgName = organizationVo.getOrgName();
                String orgCode = organizationVo.getOrgCode();
                HiddenDangerLevelCountVo hiddenDangerLevelCountVo = this.selectlevelSumByhiddenDangerLevel(orgCode, null, startDay, endDay);
                selectlevelSumByCompanyVo.setCode(orgCode);
                selectlevelSumByCompanyVo.setName(orgName);
                selectlevelSumByCompanyVo.setHiddenDangerLevelCountVo(hiddenDangerLevelCountVo);
                voList.add(selectlevelSumByCompanyVo);
            }
        }
        return voList;
    }

    /**
     * 根据公司编码-逾期统计
     * @param companyCode
     * @param mineCode
     * @param startDay
     * @param endDay
     * @return
     */
    public List<NameAndIntegerDto> overdueStatisticsByCompany(String companyCode, String mineCode, Date startDay, Date endDay) {
        //查询逾期 数量
        List<NameAndIntegerDto> list=hiddenDangerListMapper.overdueStatisticsByCompanyCount(companyCode, mineCode, startDay, endDay);

        List<NameAndIntegerDto> voList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            if (i == 0) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期一天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(0, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期一天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(0,nameAndIntegerDto);
                }
            } else if (i == 1) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期二天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(1, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期二天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(1,nameAndIntegerDto);
                }
            }else if (i == 2) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期三天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(2, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期三天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(2,nameAndIntegerDto);
                }
            }else if (i == 3) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期四天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(3, collect.get(0));
                } else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期四天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(3,nameAndIntegerDto);
                }
            }else if (i == 4) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期五天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(4, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期五天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(4,nameAndIntegerDto);
                }
            }else if (i == 5) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期六天".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(5, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期六天");
                    nameAndIntegerDto.setValue(0);
                    voList.add(5,nameAndIntegerDto);
                }
            }else if (i == 6) {
                List<NameAndIntegerDto> collect = list.stream().filter(nameAndIntegerDto -> "逾期七天以上".equals(nameAndIntegerDto.getName())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    voList.add(6, collect.get(0));
                }else {
                    NameAndIntegerDto nameAndIntegerDto = new NameAndIntegerDto();
                    nameAndIntegerDto.setName("逾期七天以上");
                    nameAndIntegerDto.setValue(0);
                    voList.add(6,nameAndIntegerDto);
                }
            }
        }

        return voList;
    }

    public HiddenDangerCountByDayVo addHiddenDangerCountByDay(String companyCode, String mineCode, Date startDay, Date endDay) {
        HiddenDangerCountByDayVo vo = new HiddenDangerCountByDayVo();
        List<String> nameList = new ArrayList<>();
        List<Integer> valueList = new ArrayList<>();

        if (startDay == null) {
            startDay = DateUtils.addDays(new Date(), -5);
        }
        Date beDate = startDay;
        if (endDay == null) {
            endDay = new Date();
        }
        long difference = endDay.getTime() - startDay.getTime();
        long differenceInDays = difference / (1000 * 60 * 60 * 24);
        List<NameAndIntegerDto> list = new ArrayList<>();
        if (differenceInDays <= 7) {
//            System.out.println("开始时间和结束时间在同一周内");
            //将开始时间设置为当前时间的前七天
            startDay = DateUtils.addDays(endDay, -7);

        } else {
            //查询一个月内的新增隐患
            startDay = DateUtils.addDays(endDay, -30);
        }
        list = hiddenDangerListMapper.addHiddenDangerCountByDay(companyCode, mineCode, startDay, endDay);

        if (list.isEmpty()) {
            vo.setValue(new ArrayList<>());
            vo.setValue(new ArrayList<>());
            return vo;
        }
        int sumCount = 0;
        for (NameAndIntegerDto nameAndIntegerDto : list) {
//            nameList.add(nameAndIntegerDto.getName());
            nameList.add(sumCount + "");
            sumCount++;
            valueList.add(nameAndIntegerDto.getValue());
        }

        //获取新增隐患总数 日期为 曲线图时间结尾的所有时间
        Integer count = hiddenDangerListMapper.addHiddenDangerCount(companyCode, mineCode, beDate, startDay);
//        NameAndIntegerDto additionalDto = new NameAndIntegerDto();
//        additionalDto.setValue(count);
//        String additionalDay = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.addDays(startDay, -1));
////        additionalDto.setName(additionalDay);
//        additionalDto.setName("更多");
//        list.add(additionalDto);
        nameList.add("更多");
        valueList.add(count);


        vo.setName(nameList);
        vo.setValue(valueList);
        return vo;


    }

    /**
     *
     * @param startDay
     * @param endDay
     * @param companyCode
     * @param mineCode
     * @return
     */
    public DangerInfoVo dangerInformationByDate(Date startDay, Date endDay, String companyCode, String mineCode) {

        if (startDay == null) {
            //今天的日期  2024-02-24 00：00：00
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startDay = calendar.getTime();
        }
        if (endDay == null) {
            endDay = new Date();
        }
        //新增隐患数量
        DangerInfoVo vo = new DangerInfoVo();
        Integer add = hiddenDangerListMapper.addHiddenDangerCount(companyCode, mineCode, startDay, endDay);
        vo.setAdded(add);

        //闭合隐患数量
        Integer close = hiddenDangerListMapper.selectCloseCountByStatus(companyCode, mineCode, startDay, endDay, Dictionaries.DANGER_STATE_CLOSEDLOOP);
        vo.setClosedLoopCount(close);


        //未闭合隐患数量
        Integer notClosedLoop = hiddenDangerListMapper.selectNotCloseCount(companyCode, mineCode, startDay, endDay, Dictionaries.DANGER_STATE_NOTCLOSEDLOOP);
        vo.setNotClosedLoopCount(notClosedLoop);


        return vo;

    }
}
